package cn.fl.ref.fncpreabslimrec.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.common.json.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncpreabslimrec.service.IFncPreAbsLimRecService;
import cn.fl.ref.fncpreabslimrec.vo.FncPreAbsLimRecVO;
import cn.fl.ref.fncpreabslimrec.vo.FncPreAbsPayRVO;
import cn.fl.ref.fncprjbscinfo.controller.FncPrjBscInfoController;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPayInsVO;
import cn.fl.system.constant.SysLogConstant;
import cn.lb.framework.poi.excel.ExcelExportUtil;
import cn.lb.framework.poi.excel.entity.ExportParams;
import cn.lb.framework.poi.excel.entity.enmus.ExcelType;
import fl.ref.fncpreabslimrec.condition.FncPreAbsLimRecQueryCondition;
import fl.ref.fncpreabspayr.condition.FncPreAbsPayRQueryCondition;
import fl.ref.fncprjpaysch.condition.FncPrjPayInsQueryCondition;


/**
 * @Description: 融资机构PRE-ABS额度使用记录表
 */
@Controller
@RequestMapping("/rfbuss/fncpreabslimrec")
public class FncPreAbsLimRecController extends BaseController {

	
	private static final Logger logger = LoggerFactory.getLogger(FncPreAbsLimRecController.class);
	@Autowired
	IFncPreAbsLimRecService fncPreAbsLimRecService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		
		logger.info("加载crbaseinfo列表页面.");
	//	String fncInsId  = request.getParameter("fncInsId");
	//	String fncInsNm  = request.getParameter("fncInsNm");
	//	String fncInsShort  = request.getParameter("fncInsShort");
		ModelAndView view = new ModelAndView("/rfbuss/fncpreabslimrec/fncpreabslimrecList");
	//	view.addObject("fncInsId", fncInsId);
	//	view.addObject("fncInsNm", fncInsNm);
	//	view.addObject("fncInsShort", fncInsShort);
		return view;
	}
	
	/**
	 * 初始化列表
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
	
	
		String id = request.getParameter("id");
	
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		FncPreAbsLimRecQueryCondition qc=new FncPreAbsLimRecQueryCondition();
		
	
		if (StringUtils.isNotEmpty(id)) {
			qc.setId(Long.parseLong(id));
		}
		
		
		page.setCondition(qc);
		
		Pager pager = this.fncPreAbsLimRecService.searchListPage(page);
		List<FncPreAbsLimRecVO> list = (List<FncPreAbsLimRecVO>) pager.getResultList();
		ListPageVO<FncPreAbsLimRecVO> listPage = new ListPageVO<FncPreAbsLimRecVO>(list, pager.getTotalCount());

		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 到授信新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String id  = request.getParameter("id");
		
		ModelAndView view = new ModelAndView("/rfbuss/fncpreabslimrec/fncPreAbsLimRecAdd");
		//view.addObject("id", id);
		return view;
	}
	
	
	
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws Exception {
String limId = request.getParameter("limId");

String batNo = request.getParameter("batNo");

String paySchId = request.getParameter("paySchId");

String limTypCd = request.getParameter("limTypCd");

String limOpAmt = request.getParameter("limOpAmt");

String isDel = request.getParameter("isDel");

String crtTm = request.getParameter("crtTm");

String crtUsrId = request.getParameter("crtUsrId");

String mdfTm = request.getParameter("mdfTm");

String mdfUsrId = request.getParameter("mdfUsrId");

		
		
		FncPreAbsLimRecVO  entity=new FncPreAbsLimRecVO();
		if (StringUtils.isNotEmpty(limId)) {
			entity.setLimId(Long.parseLong(limId));	
		}
		if (StringUtils.isNotEmpty(batNo)) {
          entity.setBatNo(batNo);
			
		}
		if (StringUtils.isNotEmpty(paySchId)) {
			
		}
		if (StringUtils.isNotEmpty(limTypCd)) {
          entity.setLimTypCd(limTypCd);
			
		}
		if (StringUtils.isNotEmpty(limOpAmt)) {
			entity.setLimOpAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(limOpAmt)));
		}
		if (StringUtils.isNotEmpty(isDel)) {
			
		}
		if (StringUtils.isNotEmpty(crtTm)) {
			entity.setCrtTm(new Date());
		}
		if (StringUtils.isNotEmpty(crtUsrId)) {
			
		}
		if (StringUtils.isNotEmpty(mdfTm)) {
			
		}
		if (StringUtils.isNotEmpty(mdfUsrId)) {
			
		}

		
		//entity.setIsvalid(BaseConstant.IS_YESNO_YES); // 有效
		entity.setIsDel(BaseConstant.IS_YESNO_NO); // 未删除
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		
		try {
			Long mainId = this.fncPreAbsLimRecService.add(entity);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("新增成功!");
			BaseLogUtils.info(logger, "add", "新增数据 ", CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			BaseLogUtils.error(logger, "add", "新增数据失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/remove.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		try {
			this.fncPreAbsLimRecService.removeById(Long.parseLong(id));
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("删除成功!");
			BaseLogUtils.info(logger, "remove", "删除数据,主键["+id+"].", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove", "删除数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "remove", "删除数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到列表页面 融资机构PRE-ABS支付表关系表
	 */
	@RequestMapping(value = "/toPayRListPage.do", method = { RequestMethod.GET})
	public ModelAndView toPayRListPage(HttpServletRequest request, HttpServletResponse response) {
		
		logger.info("加载crbaseinfo列表页面.");
	//	String fncInsId  = request.getParameter("fncInsId");
	//	String fncInsNm  = request.getParameter("fncInsNm");
	//	String fncInsShort  = request.getParameter("fncInsShort");
		ModelAndView view = new ModelAndView("/rfbase/fncPrjPayIns/fncPreAbsPayRList");
	//	view.addObject("fncInsId", fncInsId);
	//	view.addObject("fncInsNm", fncInsNm);
	//	view.addObject("fncInsShort", fncInsShort);
		return view;
	}
	
	/**
	 * 初始化列表 融资机构PRE-ABS支付表关系表
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initPayRList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initPayRList(FncPreAbsPayRQueryCondition qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
	
	
		String id = request.getParameter("id");
	
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		//FncPreAbsPayRQueryCondition qc=new FncPreAbsPayRQueryCondition();
		
	
		if (StringUtils.isNotEmpty(id)) {
			qc.setId(Long.parseLong(id));
		}
		
		
		page.setCondition(qc);
		
		Pager pager = this.fncPreAbsLimRecService.searchAbsPayRListPage(page);
		List<FncPreAbsPayRVO> list = (List<FncPreAbsPayRVO>) pager.getResultList();
		ListPageVO<FncPreAbsPayRVO> listPage = new ListPageVO<FncPreAbsPayRVO>(list, pager.getTotalCount());

		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	@RequestMapping(value = "/exportExcel.do", method = { RequestMethod.GET ,RequestMethod.POST })
	@ResponseBody
	public Object exportExcel(FncPreAbsPayRQueryCondition qc,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String currentPage = "1";
		String pageSize = "999999";
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,
				"导出成功");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.fncPreAbsLimRecService.searchAbsPayRListPage(page);
		List<FncPreAbsPayRVO> list = (List<FncPreAbsPayRVO>) pager.getResultList();
		
		try {
			// JSONArray jsonArray = JSON.parseArray(jsonArrayData);
			List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
			String filename="payR.xlsx";
			ExportParams params = new ExportParams(null, null,ExcelType.XSSF);
			params.setTitleHeight((short) 5);
	        params.setColor(HSSFColor.LIGHT_TURQUOISE.index);//表头颜色
	        params.setHeaderColor(HSSFColor.WHITE.index);//间隔颜色-未启用
			Workbook wb = ExcelExportUtil.exportExcel(params,FncPreAbsPayRVO.class,list);
			response.setHeader("Content-disposition", filename);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="
					+ filename);
			response.setHeader("Pragma", "No-cache");
			OutputStream ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
//			FncPrjBscInfoController c = new FncPrjBscInfoController();
//			c.export("资产包表-" , "资产", excelHeader, ds_titles, ds_format,
//					null, data, request, response);
		} catch (Exception e) {
			logger.error("导出文件异常", e);
		}
		return result;
	} 

}

